package MyThread_demo.ReentrantReadWriteLock_demo;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author ChenYongHao
 * @date 2023/5/4 14:32
 * @desc //提供一个 数据容器类 内部分别使用读锁保护数据的 read() 方法，写锁保护数据的 write() 方法。
 */
public class DataContainer {
    private final ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
    private int data;

    public DataContainer(int data) {
        this.data = data;
    }

    public int read() throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "获取读锁...");
        rw.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读取");
            Thread.sleep(2000);
            return data;
        } finally {
            System.out.println(Thread.currentThread().getName() + "释放读锁...");
            rw.readLock().unlock();
        }
    }

    public void write(int data) throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "获取写锁...");
        rw.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "写入");
            this.data = data;
            Thread.sleep(2000);
        } finally {
            System.out.println(Thread.currentThread().getName() + "释放写锁...");
            rw.writeLock().unlock();
        }
    }
}

